package org.example.web.response;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 响应字节数据
 */
@WebServlet("/httpServletDemo4")
public class HttpServletDemo4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //读取文件
        FileInputStream fileInputStream = new FileInputStream("E:\\图片\\wall_paper\\bing\\BBNPGrande_ZH-CN4071551965_1920x1080.jpg");
        //获取resp字节输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //完成流的copy
        /*byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }*/

        //使用IO工具类实现copy
        IOUtils.copy(fileInputStream,outputStream);
        fileInputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
